#include "os_thread.h"
#include "os_core.h"

static os_thread_manager_st g_os_thread_manager = {0};

int os_thread_create(pf_task_func_t task_func, void OS_THREAD_MEMORY * const arg, int priority)
{
    if(NULL == task_func)
    {
        return -2; // Invalid task function pointer
    }

    if(1 == g_os_thread_manager.thread_list[priority].init_flag)
    {
        return -1; // Task already exists at this priority
    }

    g_os_thread_manager.thread_list[priority].task_func = task_func;
    g_os_thread_manager.thread_list[priority].arg       =       arg;
    g_os_thread_manager.thread_list[priority].tcb.pc    =         0;
    g_os_thread_manager.thread_list[priority].tcb.tick  =         0;
    g_os_thread_manager.thread_list[priority].init_flag =         1;
    return 0; // Task created successfully
}

//调度任务
void os_thread_schedule(void)
{
    int sleep = 1;
    int     i = 0;

    g_current_thread_index = 0;
    for(; g_current_thread_index < MAX_THREAD_NUM; g_current_thread_index++)
    {
        i = g_current_thread_index;
        if(g_os_thread_manager.thread_list[i].init_flag)
        {
            if(1 == g_os_thread_manager.thread_list[i].task_func(g_os_thread_manager.thread_list[i].arg))
            {
                sleep = 0; // If task yields, set sleep flag
            }
        }
    }

    if(sleep)
    {
        port_LOWER_POWER_SLEEP(); // Lower power sleep if no task is yielding
    }
}
